<template>
    <div class="container">
        <ul class="imgUl" v-if="result">
            <li v-for="(item, index) in imgList" :key="index">
                <img :src="'/api' + item.filePath" alt="" draggable @dragstart="drag(item)">
            </li>
        </ul>
        <ul class="imgUl" v-else>
            <li v-for="(item, index) in imgList" :key="index">
                <img :src="item.filePath" alt="" draggable @dragstart="drag(item)">
            </li>
        </ul>
    </div>
</template>

<script>
import { getImageList } from './api'
export default {
    data() {
        return {
            imgList: [],
            result: true
        }
    },
    mounted() {
        this.getImageList()
    },
    methods: {
        getImageList() {
            getImageList().then(res => {
                if (res.code === 200) {
                    this.result = true
                    this.imgList = res.data
                    this.$emit('result', true)
                } else {
                    this.result = false
                    this.$emit('result', false)
                    this.getSvg()
                    this.$message.success('已启用本地资源')
                }
            }).catch(err => {
                this.result = false
                this.$emit('result', false)
                this.getSvg()
                this.$message.success('已启用本地资源')
            })
        },
        getSvg() {
            // 创建 require.context 以加载指定目录下的所有 svg, png, jpg, gif 文件
            const requireContext = require.context('/public/svg', false, /\.(svg|png|jpe?g)$/);
            // 获取所有匹配的文件
            const files = requireContext.keys()
            // 将文件转换为包含 url 属性的对象数组
            this.imgList = files.map((file) => {
                // 获取文件的实际URL
                const filePath = requireContext(file);
                return { filePath };
            });
        },
        drag(val) {
            this.$emit('change', val)
        }
    }
}
</script>

<style lang='less' scoped>
.imgUl {
    width: 100%;
    height: 100%;

    li {
        float: left;
        margin: 5px 10px;

        img {
            width: 30px;
            height: 30px;
        }
    }

    li:hover {
        background: #eee;
        cursor: pointer;
    }
}
</style>